﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace mlnx_os_sysdump_analyzer
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// true only if currently no file is loaded.        
        /// </summary>
        public bool isClear = true;

        /// <summary>
        /// pointer to the mdi parent. it will be used to dock the form.
        /// </summary>
        public MDIParent mdiParentPtr = null;
        
        /// <summary>
        /// the control layer
        /// </summary>
        FileAnalyzer fileAnalyzer = null;
        
        /// <summary>
        /// lists of the information
        /// </summary>
        ArrayList chassisInfoItems = null;
        ArrayList lspciItems = null;
        ArrayList errorsFromMessagesItems = null;
        ArrayList eithInfoItems = null;
        ArrayList runningConfigItems = null;
        ArrayList configDBItems = null;
        ArrayList mcGroupItems = null;
        ArrayList subnetInfoList = null;
        DataTable[] systemLogDataTables = null;
        string errorsFromDmesg = null;

        /// <summary>
        /// Thread handlers
        /// </summary>
        Thread loadingPanelThread = null;
        Thread loadFileThread = null;
        
        /// <summary>
        /// original form title
        /// </summary>
        private string originalFormTitle = "";
        
        /// <summary>
        /// port info status flags
        /// </summary>
        bool symbolErrorFlag = false;
        bool portStateErrorFlag = false;

        /// <summary>
        /// flags for the ports background coloring
        /// </summary>
        bool spinesPortPainted = false;
        bool IbLeafsPortPainted = false;
        bool EthLeafsPortPainted = false;
        bool loadingCompleted = false; /// this flag will be used in order to allow setting background color for the ports info table.

        // #################################
        /// <summary>
        /// holds the last keyword used for the search function
        /// </summary>
        string lastkeyword = "";

        /// <summary>
        /// variables for the search function for rich text box
        /// </summary>
        Color rtbs_lastSelectionOriginalBgColor = Color.Wheat;
        int rtbs_lastSelectedStartIndex = -1;
        int rtbs_lastSelectionLength = 1;
        string rtbs_lastTextBoxContent = "";
        RichTextBox rtbs_Last_rtb = null;
        
        /// <summary>
        /// variables for the search function for data grid view
        /// </summary>
        int dgvs_lastRow = 0;
        int dgvs_lastCol = 0;
        //
        // #################################
	
        bool isMarkersEnabled = true;
        bool markersRunOnce = true;
        
        //----------------------------------------------------
        /// <summary>
        /// init the form (font...) and save the original form title.
        /// </summary>
        private void initForm()
        {
            InitializeComponent();
            // set the font for all components
            setFontForAll();
            // save original title
            originalFormTitle = this.Text;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// constructor
        /// </summary>
        public Form1()
        {
            initForm();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="title"></param>
        public Form1(string title)
        {
            initForm();
            this.Text = title;
            originalFormTitle = title;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// chooseFileButton_Click event handler
        /// call the openFileDialog() function.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chooseFileButton_Click(object sender, EventArgs e)
        {
            if (this.MdiParent != null)
            {
                ((MDIParent)this.MdiParent).openFilesDialog();
            }
            else
            {
                openFileDialog();
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// displays the OpenFileDialog and start scanning the files.
        /// </summary>
        public void openFileDialog()
        {
            try
            {
                OpenFileDialog of = new OpenFileDialog();
                of.Filter = "All Files|*.*";
                if (of.ShowDialog() == DialogResult.OK)
                {
                    if (of.FileName != "")
                    {
                        stopAndClear();
                        fileHandler(of.FileName);                        
                    }
                }
            }
            catch
            {
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// Form1_DragDrop event handler.
        /// gets the path of the file am
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            label1.Text = "Drag and drop a sysdump file or the folder after extraction here.";
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
                    /// allow drag&drop for only one file.
                    if (filePaths.Length > 1)
                    {
                        MessageBox.Show("You can load only one file.", "Illegal input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        fileHandler(filePaths[0]);
                    }
                }
            }
            catch
            { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// Form1_DragEnter event handlers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// Form1_DragLeave event handler
        /// reset the label 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragLeave(object sender, EventArgs e)
        {
            label1.Text = "Drag and drop a sysdump file or the folder after extraction here.";
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// Form1_DragOver event handler
        /// change the label's text
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragOver(object sender, DragEventArgs e)
        {
            label1.Text = "Drop the file now to view the information.";
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// blocks the drag&drop.
        /// changes the form's titile. 
        /// displays the loading file screen.
        /// starts the file scan.
        /// </summary>
        /// <param name="path"></param>
        public void fileHandler(string path)
        {
            isClear = false;
            /// set the form's title
            this.Text += " " + path;
            /// disable the drag and drop
            try
            {
                this.AllowDrop = false;
            }
            catch
            { }
            /// display the loaidng panel
            hiddenTabsControl1.SelectedTab = this.loadingPanel;

            /// start the loadingPanel Updater thread
            loadingPanelThread = new Thread(new ThreadStart(this.loadingPanelUpdater));
            loadingPanelThread.Start();

            /// analyze the file
            fileAnalyzer = new FileAnalyzer(path);
            /// start thread
            loadFileThread = new Thread(new ThreadStart(fileAnalyzer.loadFile));
            loadFileThread.Start();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// displays the about box
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void versionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new AboutBox()).ShowDialog();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// stops the threads, and clear all fields
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            stopAndClear();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// clear all fields
        /// </summary>
        private void clearAll()
        {
            isClear = true;
            spinesPortPainted = false;
            IbLeafsPortPainted = false;
            EthLeafsPortPainted = false;
            loadingCompleted = false;

            this.Text = originalFormTitle;
            knowledgeBasePictureBox1.Image = null;
            fileAnalyzer = null;
            mcGroupDataGridView.Columns.Clear();
            mcGroupComboBox.Items.Clear();
            mcGroupParamTextBox.Text = "";
            label1.Text = "Drag and drop a sysdump file or the folder after extraction here.";
            lspciTextBox.Text = "";
            lspciComboBox.Items.Clear();
            ufmaDataTextBox.Text = "";
            ethinfoTextBox.Text = "";
            ethinfoComboBox.Items.Clear();
            systemInformationTextBox.Text = "";
            summaryTextBox.Text = "";
            chassisInfoItemsComboBox.Items.Clear();
            chassisInfoRichTextBox.Text = "";
            runningConfigTextBox.Text = "";
            runningConfigComboBox.Items.Clear();
            errorsDataGridView.Columns.Clear();
            errorsFromDmesgTextBox.Text = "";
            errorsFromMessagesComboBox.Items.Clear();
            printGapsDataGridView.Columns.Clear();
            ibPortsDataGridView.Columns.Clear();
            spinesPortInfoDataGridView.Columns.Clear();
            root_cli_historyDataGridView.Columns.Clear();
            monitor_cli_historyDataGridView.Columns.Clear();
            switchConfigurationsDataGridView.Columns.Clear();
            filesListDataGridView.Columns.Clear();
            subnetInfoDataGridView.Columns.Clear();
            ledIndicationsDataGridView.Columns.Clear();
            syslogDataGridView.Columns.Clear();
            mstdumpOnlyTextBox.Text = "";
            configDBComboBox.Items.Clear();
            configDBTextBox.Text = "";
            asicFlintLogTextBox.Text = "";
            interfaceMgmtRichTextBox.Text = "";
            linkInfoTextBox.Text = "";
            daemonsSummaryRichTextBox.Text = "";

            daemonsDataGridView.Columns.Clear();
            issPortDBDataGridView.Columns.Clear();
            port_indexes_htDataGridView.Columns.Clear();
            lagCacheTextBox.Text = "";
            interfaces_htDataGridView.Columns.Clear();
            issdPFCDataGridView.Columns.Clear();
            issdETSTextBox.Text = "";
            vlanMembersDataGridView.Columns.Clear();

            // allow the drag and drop
            //if (Form1.ActiveForm != null)
            //{
            //    this.AllowDrop = true;
            //}
            // show the file load panel
            hiddenTabsControl1.SelectedTab = this.filLoadPanel;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// update the loading panel.
        /// display the information after the scan is complete.
        /// </summary>
        private void loadingPanelUpdater()
        {
            while (true)
            {
                loadingPanelAccessControl();
            }
        }
        // accesses a vaiable of another thread.
        private void loadingPanelAccessControl()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(loadingPanelAccessControl));
                }
                else
                {
                    if (fileAnalyzer != null)
                    {
                        if (fileAnalyzer.isDone == true)
                        {
                            // show main panel
                            displayInfo();
                            if (fileAnalyzer.loadedLogsFile == false)
                            {
                                hiddenTabsControl1.SelectedTab = this.mstdumpOnlyPanel;
                            }
                            else
                            {
                                hiddenTabsControl1.SelectedTab = this.mainPanel;
                            }
                            stopThreads();
                            //
                            fileAnalyzer = null;
                        }
                    }
                }
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// Form1_FormClosing event handler.
        /// stops all threads.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopAndClear();
            fileAnalyzer = null;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// exitToolStripMenuItem_Click handler.
        /// stops all threads.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            stopAndClear();
            this.Close();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// openToolStripMenuItem_Click handler.
        /// display the open file dialog.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// stops all threads
        /// </summary>
        private void stopThreads()
        {
            /// stop threads
            if (fileAnalyzer != null)
            {
                fileAnalyzer.KEEP_RUNNING = false;
            }
            if (loadingPanelThread != null && loadingPanelThread.IsAlive)
            {
                loadingPanelThread.Abort();
            }
            /// reset
            loadFileThread = null;
            loadingPanelThread = null;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// cancelBtn_Click handler.
        /// stops the sysdump scanning.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cancelBtn_Click(object sender, EventArgs e)
        {
            stopAndClear();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// stops the threads and clears all fileds.
        /// </summary>
        public void stopAndClear()
        {
            stopThreads();
            clearAll();
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// gets the info from the control layer to the view layer.
        /// </summary>
        private void displayInfo()
        {
            try
            {
                if (fileAnalyzer != null)
                {
                    /// if only mstdump file was loaded
                    if (fileAnalyzer.loadedLogsFile == false)
                    {
                        mstdumpOnlyTextBox.Text = fileAnalyzer.getMstdumpInfo();
                    }
                    else /// if the input wasn't mstdump file
                    {
                        summaryTextBox.Text = "";
                        // clear the leafs table and show the data
                        ibPortsDataGridView.Columns.Clear();
                        //ibPortsDataGridView.DataSource = fileAnalyzer.portInfoScanner.getLeafsPortInfo();
                        ibPortsDataGridView.DataSource = fileAnalyzer.portInfoScanner.getIBPortsTable();
                        ethPortsDataGridView.Columns.Clear();
                        ethPortsDataGridView.DataSource = fileAnalyzer.portInfoScanner.getETHPortsTable();
                        // clear the spines table and show the data
                        spinesPortInfoDataGridView.Columns.Clear();
                        spinesPortInfoDataGridView.DataSource = fileAnalyzer.portInfoScanner.getSpinePortsTable();
                        
                        
                        // display the device information
                        systemInformationTextBox.Text = fileAnalyzer.systemInfo;
                        systemInformationTextBox.Text += "\r\nU-Boot version:\r\n" + fileAnalyzer.messagesScanner.uBootVersoin;
                        //
                        interfaceMgmtRichTextBox.Text = fileAnalyzer.ChassisInfoScanner.interfaceMgmt;
                        addBgColorForRichTextBox(interfaceMgmtRichTextBox);
                        chassisInfoItems = fileAnalyzer.ChassisInfoScanner.getChassisItemsInfo();
                        addItemsToComboBox(chassisInfoItemsComboBox, chassisInfoItems, chassisInfoRichTextBox);
                        addBgColorForRichTextBox(chassisInfoRichTextBox);
                        //
                        lspciItems = fileAnalyzer.lspciItems;
                        addItemsToComboBox(lspciComboBox, lspciItems, lspciTextBox);
                        //
                        errorsFromMessagesItems = fileAnalyzer.messagesScanner.getErrors();
                        addItemsToErrorsComboBox(errorsFromMessagesComboBox, errorsFromMessagesItems);
                        errorsDataGridView.DefaultCellStyle.Format = "MMM d hh:mm:ss";
                        (new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
                        //
                        printGapsDataGridView.DataSource = fileAnalyzer.messagesScanner.logsPrintGaps;
                        printGapsDataGridView.Columns["Time 1"].DefaultCellStyle.Format = "MMM d hh:mm:ss";
                        printGapsDataGridView.Columns["Time 2"].DefaultCellStyle.Format = "MMM d hh:mm:ss";
                        //
                        daemonsDataGridView.DataSource = fileAnalyzer.messagesScanner.getDaemonsList();
                        daemonsDataGridView.Sort(daemonsDataGridView.Columns["Time"], ListSortDirection.Descending);
                        daemonsDataGridView.DefaultCellStyle.Format = "MMM d hh:mm:ss";
                        daemonsSummaryRichTextBox.Text = fileAnalyzer.messagesScanner.getDaemonsSummary();
                        //
                        eithInfoItems = fileAnalyzer.ethInfoScanner.getEthInfo();
                        addItemsToComboBox(ethinfoComboBox, eithInfoItems, ethinfoTextBox);
                        //
                        switchConfigurationsDataGridView.DataSource = fileAnalyzer.switchConfigurationsScanner.getSwitchConfigurations();
                        //
                        runningConfigItems = fileAnalyzer.runningConfigScanner.getRunningConfig();
                        addItemsToComboBox(runningConfigComboBox, runningConfigItems, runningConfigTextBox);
                        //
                        filesListDataGridView.DataSource = fileAnalyzer.filesListScanner.getFilesList();
                        filesListDataGridView.Sort(filesListDataGridView.Columns["Size [bytes]"], ListSortDirection.Descending);
                        //
                        root_cli_historyDataGridView.DataSource = fileAnalyzer.rootCMDHistory.getCommandHistory();
                        //
                        monitor_cli_historyDataGridView.DataSource = fileAnalyzer.monitorCMDHistory.getCommandHistory();
                        //
                        ufmaDataTextBox.Text = fileAnalyzer.ufmaData;
                        //
                        errorsFromDmesg = fileAnalyzer.dmesgScanner.getErrors();
                        
                        //errorsFromDmesgTextBox.Text = errorsFromDmesg[0];
                        setErrorsFromDmesgContent();
                        //
                        try
                        {
                            configDBItems = fileAnalyzer.configDBContent;
                            string active = fileAnalyzer.runningConfigScanner.getActiveConfigFile();
                            for (int i = 0; i < configDBItems.Count; i++)
                            {
                                if (active.Equals(((Item)configDBItems[i]).itemName))
                                {
                                    ((Item)configDBItems[i]).itemName = active + "     -------> This is the active config file.";
                                    break;
                                }
                            }
                            addItemsToComboBox(configDBComboBox, configDBItems, configDBTextBox);
                        }
                        catch { }
                        //
                        issPortDBDataGridView.DataSource = fileAnalyzer.issDumpScanner.getIssPortDBList();
                        port_indexes_htDataGridView.DataSource = fileAnalyzer.issDumpScanner.getPortIndexesHtList();
                        lagCacheTextBox.Text = fileAnalyzer.issDumpScanner.getIssdLAGCache();
                        interfaces_htDataGridView.DataSource = fileAnalyzer.issDumpScanner.getinterfaces_ht_List();
                        issdPFCDataGridView.DataSource = fileAnalyzer.issDumpScanner.getIssdPFCCacheList();
                        issdETSTextBox.Text = fileAnalyzer.issDumpScanner.getIisdETSCache();
                        vlanMembersDataGridView.DataSource = fileAnalyzer.issDumpScanner.getVlanMembersList();

                        //
                        processesDataGridView.DataSource = fileAnalyzer.processesScanner.getProcessesList();
                        processesDataGridView.Sort(processesDataGridView.Columns["VSZ"], ListSortDirection.Descending);
                        memoryUsageTextBox.Text = fileAnalyzer.processesScanner.getOutputOfFree();
                        asicFlintLogTextBox.Text = fileAnalyzer.asicFlintLog;
                        //
                        // MC Groups
                        try
                        {
                            mcGroupItems = fileAnalyzer.openSMScanner.getMCGroupsList();
                            if (mcGroupItems != null && mcGroupItems.Count > 0)
                            {
                                // add items to the combo box
                                for (int i = 0; i < mcGroupItems.Count; i++)
                                {
                                    mcGroupComboBox.Items.Add(Regex.Split((string)((object[])mcGroupItems[i])[0], "\r\n")[0]);
                                }
                                // select first item
                                mcGroupComboBox.SelectedIndex = 0;
                                // show the content of the first item
                                mcGroupParamTextBox.Text = (string)((object[])mcGroupItems[0])[0];
                                mcGroupDataGridView.DataSource = ((object[])mcGroupItems[1])[1];
                            }
                        }
                        catch { }
                        // subnet info
                        Object[] subnetInfoData = fileAnalyzer.openSMScanner.getSubnetInfo();
                        subnetInfoDataGridView.DataSource = subnetInfoData[0];
                        subnetInfoList = (ArrayList)subnetInfoData[1];
                        //
                        ledIndicationsDataGridView.DataSource = fileAnalyzer.messagesScanner.getLedIndications();
                        ledIndicationsDataGridView.Sort(ledIndicationsDataGridView.Columns["Time"], ListSortDirection.Descending);
                        ledIndicationsDataGridView.DefaultCellStyle.Format = "MMM d hh:mm:ss";
                        //
                        systemLogDataTables = fileAnalyzer.syslogScanner.getSystemLog();
                        syslogDataGridView.DataSource = systemLogDataTables[0];
                        //


                        // #############################
                        // Fill Summary tab

//                        double dsize = (double)fileAnalyzer.filesListScanner.getTotalFilesSize();
//                        double vmsize = (double)fileAnalyzer.processesScanner.getTotalVirtualMemoryInUse();
//                        double rss = (double)fileAnalyzer.processesScanner.getTotalRealMemoryInUse();
//                        summaryTextBox.Text += "* Sum of files' size (from File list) is: " + dsize + " bytes {= " + Methods.RoundDoubleDigits(dsize / 1024) + " KB = " + Methods.RoundDoubleDigits(dsize / 1048576) + " MB = " + Methods.RoundDoubleDigits(dsize / 1073741824) + " GB }\r\n";
//                        summaryTextBox.Text += "* Sum of VSZ column (in the output of 'ps') is: " + vmsize + " KB {= " + Methods.RoundDoubleDigits(vmsize / 1024) + " MB = " + Methods.RoundDoubleDigits(vmsize / 1048576) + " GB}\r\n";
//                        summaryTextBox.Text += "* Sum of RSS column (in the output of 'ps') is: " + rss + " KB {= " + Methods.RoundDoubleDigits(rss / 1024) + " MB = " + Methods.RoundDoubleDigits(rss / 1048576) + " GB}\r\n\r\n";
                        //
                        summaryTextBox.Text += "* Scanned ports:\r\n"
                                + "\tIB ports#: " +ibPortsDataGridView.Rows.Count + "\r\n"
                                + "\tETH ports#: " + ethPortsDataGridView.Rows.Count + "\r\n\r\n";
                        //
                        summaryTextBox.Text += "* " +fileAnalyzer.messagesScanner.getPowerOnCounter() + "\r\n\r\n";
                        //
                        if (fileAnalyzer.filesListScanner.getImgCount() > 1)
                        {
                            summaryTextBox.Text += "* There are " + fileAnalyzer.filesListScanner.getImgCount()
                                + " image files on the switch.\r\n"
                                + "--> delete the old image files."
                                + "\r\n\r\n";
                        }
                        //
                        if (fileAnalyzer.filesListScanner.getTgzCount() > 1)
                        {
                            summaryTextBox.Text += "* There are " + fileAnalyzer.filesListScanner.getTgzCount()
                                + " 'tgz' files on the switch.\r\n"
                                + "--> delete the old tgz files."
                                + "\r\n\r\n";
                        }
                        //
                        if (fileAnalyzer.ChassisInfoScanner.timeouts || fileAnalyzer.portInfoScanner.getTimeoutState())
                        {
                            summaryTextBox.Text += "* In sysinfo.txt file: Some commands were interrupted due to timeout."
                                + "\r\n\r\n";
                        }
                        //
                        if (symbolErrorFlag)
                        {
                            summaryTextBox.Text += "* Some ports have symbole errors."
                                + "\r\n\r\n";
                        }
                        //
                        if (portStateErrorFlag)
                        {
                            summaryTextBox.Text += "* Some ports have are down/not linked up."
                                + "\r\n\r\n";
                        }
                        //
                        summaryTextBox.Text += fileAnalyzer.messagesScanner.getDaemonsLoadVerification()
                                + "\r\n\r\n";
                        //
                        //summaryTextBox.Text += fileAnalyzer.dmesgScanner.checkForPLBerr();
                        if (errorsFromDmesg.Contains("PLB"))
                        {
                            summaryTextBox.Text += "* ERROR: There are PLB errors on the switch.\r\n"
                               + "More details can be found under the 'Errors' -> 'From dmesg' tab."
                               + "\r\n\r\n";
                        }
                        //
                        summaryTextBox.Text += fileAnalyzer.ChassisInfoScanner.mgmtStatus;
                        //
                        if (fileAnalyzer.messagesScanner.logsPrintGaps.Rows.Count > 0)
                        {
                            summaryTextBox.Text += "* WARNING: There were no prints to the messages files for more than " + Properties.Settings.Default.logsIdleThresholdSec + " seconds."
                                + "\r\nMore details can be found under the 'Messages' tab."
                                + "\r\n\r\n";
                        }
                        //
                        if (root_cli_historyDataGridView.Rows.Count == 0)
                        {
                            summaryTextBox.Text += "* ERROR: The 'root_cli_history' file is empty."
                                + "\r\n\r\n";
                        }
                        //

                        /// #############################
                        /// display the asic picture according to the P/N
                        switch (fileAnalyzer.ChassisInfoScanner.partNumber)
                        {
                            case "SX1016":
                            case "SX1024":
                            case "SX1035":
                            case "SX1036":
                                knowledgeBasePictureBox1.Image = Properties.Resources.SX10XX;
                                systemInformationTextBox.Text += "\r\n\r\n" + fileAnalyzer.getMstdumpInfo();
                                break;
                            case "SX6018":
                            case "SX6036":
                                knowledgeBasePictureBox1.Image = Properties.Resources.SX60XX;
                                systemInformationTextBox.Text += "\r\n\r\n" + fileAnalyzer.getMstdumpInfo();
                                break;
                            case "SX6518":
                                knowledgeBasePictureBox1.Image = Properties.Resources.SX6518;
                                break;
                            case "SX6536":
                                knowledgeBasePictureBox1.Image = Properties.Resources.SX6536;
                                break;
                            default:
                                break;
                        } /// end of switch
                        /// #############################
                        //
                    }
                    /// update this flag in order to allow setting background color for the ports info table.
                    loadingCompleted = true;
                }
                else
                {
                    clearAll();
                    /// we didn't scan all information, so no need to set background color for the ports info table.
                    loadingCompleted = false;
                }

                if (fileAnalyzer != null)
                {
                    fileAnalyzer.Dispose();
                }
            }
            catch { }
            
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// add items to a combo box.
        /// </summary>
        /// <param name="cb">target combo box</param>
        /// <param name="items">items list</param>
        /// <param name="tb">relevant text box that displays the information for the selected item in the combo box</param>
        private void addItemsToComboBox(ComboBox cb, ArrayList items, Object tb)
        {
            try
            {
                if (items != null && cb != null && tb != null)
                {
                    /// add all items to the combo box
                    for (int i = 0; i < items.Count; i++)
                    {
                        cb.Items.Add(((Item)items[i]).itemName);
                    }
                    /// if there was at least one item added to the combo box, then display the relevant infromation in the text box.
                    if (cb.Items.Count > 0)
                    {
                        /// select first item
                        cb.SelectedIndex = 0;
                        /// display the information
                        if (tb is TextBox)
                        {
                            ((TextBox)tb).Text = ((Item)items[0]).content;
                        }
                        else
                        {
                            if (tb is RichTextBox)
                            {
                                ((RichTextBox)tb).Text = ((Item)items[0]).content;
                            }
                        }
                    }
                }
            }
            catch { }

        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// add items to the combo box in the messages tab, and checks the radio button
        /// </summary>
        /// <param name="cb">target combo box</param>
        /// <param name="items">items list</param>
        private void addItemsToErrorsComboBox(ComboBox cb, ArrayList items)
        {
            try
            {
                if (items != null && cb != null)
                {
                    /// add all the items
                    for (int i = 0; i < items.Count; i++)
                    {
                        cb.Items.Add(((ErrorsFields)items[i]).fileName);
                    }
                    /// if there was at least one item added to the combo box, then display the relevant infromation in the text box.
                    if (cb.Items.Count > 0)
                    {
                        /// select first item
                        cb.SelectedIndex = 0;
                        /// select the errors only radio button
                        errorsOnlyRadioButton.Checked = true;
                        /// display the relevant information
                        setErrorTableContent();//errorsDataGridView.DataSource = ((ErrorsFields)items[0]).errorsOnly;
                    }
                }
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// add background color for the cells in the port info table
        /// </summary>
        /// <param name="param">DataGridView</param>
        private void addBgColorForErrorsIn_IB_Ports(object param)
        {
            DataGridView dgv = (DataGridView)param;
            string[] arr = null;
            for (int row = 0; row < dgv.RowCount; row++)
            {
                try
                {
                    // set default background color
                    dgv.Rows[row].DefaultCellStyle.BackColor = Color.LimeGreen;
                }
                catch { }
                //########################################################################
                // IB ports
                try
                {
                    // check width
                    arr = Regex.Split((string)dgv.Rows[row].Cells["Supported widths"].Value, ",");
                    if (!dgv.Rows[row].Cells["Width"].Value.Equals(arr[arr.Length - 1]))
                    {
                        dgv.Rows[row].DefaultCellStyle.BackColor = Color.Yellow;
                    }
                    // check speed
                    if (((string)dgv.Rows[row].Cells["Supported speeds"].Value).Contains("or"))
                    {
                        arr = Regex.Split((string)dgv.Rows[row].Cells["Supported speeds"].Value, "or");
                    }
                    else if (((string)dgv.Rows[row].Cells["Supported speeds"].Value).Contains("/"))
                    {
                        arr = Regex.Split((string)dgv.Rows[row].Cells["Supported speeds"].Value, "/");
                    }
                    else
                    {
                        arr = Regex.Split((string)dgv.Rows[row].Cells["Supported speeds"].Value, ",");
                    }
                    if (!dgv.Rows[row].Cells["Speed"].Value.Equals(arr[arr.Length - 1]))
                    {
                        dgv.Rows[row].DefaultCellStyle.BackColor = Color.Yellow;
                    }
                    //
                    try
                    {
                        // check connected device
                        if (dgv.Rows[row].HeaderCell.Value != null && dgv.Rows[row].HeaderCell.Value.Equals("Connected device active")) // is it a spine port ?
                        {
                            if ((int)dgv.Rows[row].Cells["Connected device active"].Value != 1)
                            {
                                dgv.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                                symbolErrorFlag = true;
                            }
                        }
                    }
                    catch { }
                    // check port state
                    if (dgv.Rows[row].Cells["Logical port state"].Value.Equals(" Down") ||
                        !dgv.Rows[row].Cells["Physical port state"].Value.Equals(" LinkUp"))
                    {
                        dgv.Rows[row].DefaultCellStyle.BackColor = Color.LightSalmon;
                        portStateErrorFlag = true;
                    }
                    // check errors
                    if (dgv.Rows[row].HeaderCell.Value != null && (dgv.Rows[row].HeaderCell.Value.Equals("Symbol errors") || dgv.Rows[row].HeaderCell.Value.Equals("RX errors")))
                    {
                        if ((long)dgv.Rows[row].Cells["Symbol errors"].Value > 0 ||
                            (long)dgv.Rows[row].Cells["RX errors"].Value > 0)
                        {
                            dgv.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                            symbolErrorFlag = true;
                        }
                    }
                    if (dgv.Rows[row].HeaderCell.Value != null && dgv.Rows[row].HeaderCell.Value.Equals("Error state")) // is it a spine port ?
                    {
                        if ((int)dgv.Rows[row].Cells["Error state"].Value > 0)
                        {
                            dgv.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                            symbolErrorFlag = true;
                        }
                    }
                    //
                }
                catch { }
            }// end of for
            
        }
        //
        //----------------------------------------------------

        /// <summary>
        /// add background color for the cells in the port info table
        /// </summary>
        /// <param name="param">DataGridView</param>
        private void addBgColorForErrorsIn_ETH_Ports(object param)
        {
            DataGridView dgv = (DataGridView)param;
            for (int row = 0; row < dgv.RowCount; row++)
            {
                try
                {
                    // set default background color
                    dgv.Rows[row].DefaultCellStyle.BackColor = Color.LimeGreen;
                }
                catch { }
                //########################################################################
                // Eth ports
                try
                {
                    if (!dgv.Rows[row].Cells["Admin state"].Value.Equals(" Enabled") ||
                        !dgv.Rows[row].Cells["Operational state"].Value.Equals(" Up"))
                    {
                        dgv.Rows[row].DefaultCellStyle.BackColor = Color.LightSalmon;
                        portStateErrorFlag = true;
                    }

                    if ((long)dgv.Rows[row].Cells["RX error frames"].Value > 0)
                    {
                        dgv.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                        symbolErrorFlag = true;
                    }
                }
                catch { }
                //########################################################################
            }// end of for

        }
        //
        //----------------------------------------------------



        /// <summary>
        /// chassisInfoItemsComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chassisInfoItemsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = chassisInfoItemsComboBox.SelectedIndex;
                /// display relevant info
                chassisInfoRichTextBox.Text = ((Item)chassisInfoItems[index]).content;
                /// put bg colors
                addBgColorForRichTextBox(chassisInfoRichTextBox);
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// lspciComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lspciComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = lspciComboBox.SelectedIndex;
                /// display relevant info
                lspciTextBox.Text = ((Item)lspciItems[index]).content;
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// errorsFromMessagesComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void errorsFromMessagesComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                setErrorTableContent();
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// ethinfoComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ethinfoComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = ethinfoComboBox.SelectedIndex;
                /// display relevant info
                ethinfoTextBox.Text = ((Item)eithInfoItems[index]).content;
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// runningConfigComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void runningConfigComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = runningConfigComboBox.SelectedIndex;
                /// display relevant info
                runningConfigTextBox.Text = ((Item)runningConfigItems[index]).content;
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// configDBComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void configDBComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = configDBComboBox.SelectedIndex;
                /// display relevant info
                configDBTextBox.Text = ((Item)configDBItems[index]).content;
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// mcGroupComboBox_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mcGroupComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                /// get selected index
                int index = mcGroupComboBox.SelectedIndex;
                /// display relevant info
                mcGroupDataGridView.Columns.Clear();
                mcGroupDataGridView.DataSource = ((object[])mcGroupItems[index])[1];
                mcGroupParamTextBox.Text = (string)((object[])mcGroupItems[index])[0];
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// leafsPortInfoDataGridView_CellContentDoubleClick event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void leafsPortInfoDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string target = "";
                bool toNavigate = false;
                if (ibPortsDataGridView.Columns[e.ColumnIndex].Name.Equals("Cable serial number"))
                {
                    // search for the S/N in SF
                    target = (string)ibPortsDataGridView.Rows[e.RowIndex].Cells["Cable serial number"].Value;
                    toNavigate = true;
                }
                if (ibPortsDataGridView.Columns[e.ColumnIndex].Name.Equals("Cable part number"))
                {
                    // search for the P/N in SF
                    target = (string)ibPortsDataGridView.Rows[e.RowIndex].Cells["Cable part number"].Value;
                    toNavigate = true;
                }
                if (toNavigate)
                {
                    Methods.RunProcess("https://na3.salesforce.com/_ui/common/search/client/ui/UnifiedSearchResults?asPhrase=1&searchType=2&sen=a1G&sen=01t&sen=a0F&sen=a0E&sen=a0H&sen=005&sen=00P&sen=00Q&sen=a0L&sen=501&sen=001&sen=a1J&sen=00T&sen=015&sen=00U&sen=500&sen=003&sen=a0O&sen=00a&str=+"
                        + target
                        + "&cache=h8czj62g");
                }
            }
            catch
            { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// add background for special words in a rich text box.
        /// </summary>
        /// <param name="rtb">RichTextBox</param>
        private void addBgColorForRichTextBox(RichTextBox rtb)
        {
            /// define the words to be colored
            string[] greenBg = new string[] { "Device configured", "DEVICE_OK", "OK", "ok ", "Module ok", " 1 ", "yes", "enabled ", "running ", "(active" };
            string[] redBg = new string[] { "Powered off", "FATAL CONDITION I2C error", "NOT PRESENT", "no ", "failure", "Not present", " 0 ", "bad", "  no" , "NO", "Fatal state"};
            string[] yellowBg = new string[] { "N/A", "n/a" };

            object[] keywords = new object[] { greenBg, redBg, yellowBg };
            Color[] colors = new Color[] { Color.Green, Color.Red, Color.Yellow };
            /// scann for all the words and highlight them
            for (int arrNum = 0; arrNum < keywords.Length; arrNum++)
            {
                for (int j = 0; j < ((string[])keywords[arrNum]).Length; j++)
                {
                    int index = -1;
                    int length = 1;
                    while (rtb.Find(((string[])keywords[arrNum])[j], index + length, rtb.Text.Length, RichTextBoxFinds.WholeWord) >= 0) // if found it 
                    {
                        // save the indexes and color of this word
                        index = rtb.SelectionStart;
                        length = rtb.SelectionLength;
                        //
                        rtb.SelectionBackColor = colors[arrNum];
                    }
                }
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// searches for the given keyword in the current selected tab.
        /// </summary>
        /// <param name="keyword">keyword to seach for</param>
        /// <returns></returns>
        public bool searchInCurrentTab(string keyword)
        {            
            // #####
            /// clear the last highlight
            resetBgColorForSelections();
            // #####
            if (hiddenTabsControl1.SelectedTab.Text.Equals(mstdumpOnlyPanel.Text))
            {
                return searchInRichTextBox(mstdumpOnlyTextBox, keyword);
            }
            if (hiddenTabsControl1.SelectedTab.Text.Equals(mainPanel.Text))
            {
                // chassisInfoTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(chassisInfoTab.Text) && chassisInfoMainTab.SelectedTab.Text.Equals(chassisInfoTab1.Text))
                {
                    return searchInRichTextBox(chassisInfoRichTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(chassisInfoTab.Text) && chassisInfoMainTab.SelectedTab.Text.Equals(ledIndicationsTab.Text))
                {
                    return searchInDataGridView(ledIndicationsDataGridView, keyword);
                }
                // interfaceMgmtTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(interfaceMgmtTab.Text))
                {
                    return searchInRichTextBox(interfaceMgmtRichTextBox, keyword);
                }
                // daemonsTabPage
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(daemonsTabPage.Text) && daemonMainTabControl.SelectedTab.Text.Equals(daemonsSummaryTabPage.Text))
                {
                    return searchInRichTextBox(daemonsSummaryRichTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(daemonsTabPage.Text) && daemonMainTabControl.SelectedTab.Text.Equals(daemonsHistoryTabPage.Text))
                {
                    return searchInDataGridView(daemonsDataGridView, keyword);
                }
                //knowledgeBaseTab summary
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(summaryTab.Text))
                {
                    return searchInRichTextBox(summaryTextBox, keyword);
                }
                //systemInformationTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(systemInformationTab.Text) && systemInformationMainTab.SelectedTab.Text.Equals(softwareVersionTab.Text))
                {
                    return searchInRichTextBox(systemInformationTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(systemInformationTab.Text) && systemInformationMainTab.SelectedTab.Text.Equals(imageHistoryTab.Text))
                {
                    return searchInDataGridView(syslogDataGridView, keyword);
                }
                // messagesTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(messagesTab.Text) && errorsMainTab.SelectedTab.Text.Equals(errorsInMessagesTab.Text))
                {
                    lock (markerLock)
                    {
                        isMarkersEnabled = false;

                        // search only in current opened messages file.
                        if (searchInChosenMessagesRadioButton.Checked)
                        {
                            return searchInDataGridView(errorsDataGridView, keyword);
                        }
                        else // search in all messages files.
                        {
                            // get the display style (errors only or full content).
                            bool displayErrsOnly = errorsOnlyRadioButton.Checked;

                            int index = errorsFromMessagesComboBox.SelectedIndex;
                            /// save the first index in order to stop when we reach it again  
                            /// (this will make sure that we will scan each file only once).
                            int startIndex = index;
                            bool fisrtFilesScanned = false;

                            for (; true; ++index)
                            {
                                /// check if we should go back to the first file in the list.
                                if (index == errorsFromMessagesItems.Count)
                                {
                                    index = 0;
                                }
                                /// check if we return to the fist file
                                if (index == startIndex && fisrtFilesScanned == true)
                                {
                                    /// stop the search, and return false.
                                    isMarkersEnabled = true;
                                    (new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
                                    return false;
                                }
                                else
                                {
                                    fisrtFilesScanned = true;
                                }

                                // select a file --> this will also update the datagridveiw
                                errorsFromMessagesComboBox.SelectedIndex = index;
                                
                                // show errors only 
                                //if (displayErrsOnly == true)
                                //{
                                //    errorsDataGridView.DataSource = ((ErrorsFields)errorsFromMessagesItems[index]).errorsOnly;
                                //}
                                //else // show the full content
                                //{
                                //    errorsDataGridView.DataSource = ((ErrorsFields)errorsFromMessagesItems[index]).fullContent;
                                //}
                                //errorsDataGridView.Refresh();

                                // start searching
                                if (searchInDataGridView(errorsDataGridView, keyword))
                                {
                                    /// if we found a match, stop the search.
                                    isMarkersEnabled = true;
                                    (new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
                                    return true;
                                }
                            } // end for
                        }// end else
                    }// end lock
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(messagesTab.Text) && errorsMainTab.SelectedTab.Text.Equals(errorsInDmesgTab.Text))
                {
                    return searchInRichTextBox(errorsFromDmesgTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(messagesTab.Text) && errorsMainTab.SelectedTab.Text.Equals(printGapsTabPage.Text))
                {
                    return searchInDataGridView(printGapsDataGridView, keyword);
                }
                //configDBMain
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(configurationDBTab.Text) && configDBMain.SelectedTab.Text.Equals(runningConfigTab.Text))
                {
                    return searchInRichTextBox(runningConfigTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(configurationDBTab.Text) && configDBMain.SelectedTab.Text.Equals(configDBTab.Text))
                {
                    return searchInRichTextBox(configDBTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(configurationDBTab.Text) && configDBMain.SelectedTab.Text.Equals(activeTab.Text))
                {
                    return searchInDataGridView(switchConfigurationsDataGridView, keyword);
                }
                // ibInfoTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ibInfoTab.Text) && ibInfoMainTab.SelectedTab.Text.Equals(mutlicastGroupsTab.Text))
                {
                    return searchInRichTextBox(mcGroupParamTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ibInfoTab.Text) && ibInfoMainTab.SelectedTab.Text.Equals(subnetTopologyTab.Text))
                {
                    return searchInDataGridView(subnetInfoDataGridView, keyword);
                }
                // ethInfoMainTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(ethinfoTab.Text))
                {
                    return searchInRichTextBox(ethinfoTextBox, keyword);
                }

                // ethInfoMainTab -> ISS dump
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(LAGCacheTab.Text))
                {
                    return searchInRichTextBox(lagCacheTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(ISSDETSTab.Text))
                {
                    return searchInRichTextBox(issdETSTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(issPortDBTab.Text))
                {
                    return searchInDataGridView(issPortDBDataGridView, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(port_indexes_htTab.Text))
                {
                    return searchInDataGridView(port_indexes_htDataGridView, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(interfaces_htTAb.Text))
                {
                    return searchInDataGridView(interfaces_htDataGridView, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(issdPFCTab.Text))
                {
                    return searchInDataGridView(issdPFCDataGridView, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ethInfoTabs.Text) && ethInfoMainTab.SelectedTab.Text.Equals(issdumpTab.Text) && issDumpMainTab.SelectedTab.Text.Equals(vlanMembersTab.Text))
                {
                    return searchInDataGridView(vlanMembersDataGridView, keyword);
                }
                // processesAndMemoryTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(processesAndMemoryTab.Text) && processesAndMemoryMainTab.SelectedTab.Text.Equals(memoryUsageTab.Text))
                {
                    return searchInRichTextBox(memoryUsageTextBox, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(processesAndMemoryTab.Text) && processesAndMemoryMainTab.SelectedTab.Text.Equals(runningProcessesTab.Text))
                {
                    return searchInDataGridView(processesDataGridView, keyword);
                }
                // lspciTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(lspciTab.Text))
                {
                    return searchInRichTextBox(lspciTextBox, keyword);
                }
                // asicFintLogTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(asicFintLogTab.Text))
                {
                    return searchInRichTextBox(asicFlintLogTextBox, keyword);
                }
                // ufmaDataTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(ufmaDataTab.Text))
                {
                    return searchInRichTextBox(ufmaDataTextBox, keyword);
                }
                // portInfoTab
                // ib
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(ibPortsTab.Text))
                {
                    return searchInDataGridView(ibPortsDataGridView, keyword);
                }
                // eth
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(ethPortsTab.Text))
                {
                    return searchInDataGridView(ethPortsDataGridView, keyword);
                }
                // spines
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(portsInfoSpinesTab.Text))
                {
                    return searchInDataGridView(spinesPortInfoDataGridView, keyword);
                }
                // commandsHistoryTab
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(commandsHistoryTab.Text) && commandsHistoryMainTab.SelectedTab.Text.Equals(root_cli_historyTab.Text))
                {
                    return searchInDataGridView(root_cli_historyDataGridView, keyword);
                }
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(commandsHistoryTab.Text) && commandsHistoryMainTab.SelectedTab.Text.Equals(monitor_cli_historyTab.Text))
                {
                    return searchInDataGridView(monitor_cli_historyDataGridView, keyword);
                }
                //
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(filesListTab.Text))
                {
                    return searchInDataGridView(filesListDataGridView, keyword);
                }
            }
            //
            return false;
        }
        //
        //----------------------------------------------------
        // 
        /// <summary>
        /// searches for the given keyword in a RichTextBox
        /// </summary>
        /// <param name="rtb">RichTextBox</param>
        /// <param name="keyword">keyword</param>
        /// <returns>retruns true if it finds a match for the keyword</returns>
        private bool searchInRichTextBox(RichTextBox rtb, string keyword)
        {
            // ### the following global varibales are declared above. ###
            // lastSelectionOriginalBgColor = Color.Wheat;
            // lastSelectedStartIndex = 0;
            // lastSelectionLength = 0;
            // lastTextBoxContent = "";
            // lastkeyword = "";
            bool flag = false;
            //
            try
            {
                /// clear the last highlight
                resetBgColorForSelections();
                rtbs_Last_rtb = rtb;
                if (!rtbs_lastTextBoxContent.Equals(rtb.Text) || !lastkeyword.Equals(keyword))
                { 
                    //reset all variables
                    rtbs_lastSelectionOriginalBgColor = Color.Wheat;
                    rtbs_lastSelectedStartIndex = -1;
                    rtbs_lastSelectionLength = 1;
                    rtbs_lastTextBoxContent = rtb.Text;
                    lastkeyword = keyword;
                }
                //
                if (rtb != null && rtb.Text.Length > 0)
                {
                    if (rtb.Find(keyword, rtbs_lastSelectedStartIndex + rtbs_lastSelectionLength, rtb.Text.Length, RichTextBoxFinds.None) >= 0) // if found it 
                    {
                        // save the indexes and color of this word
                        rtbs_lastSelectionOriginalBgColor = rtb.SelectionBackColor;
                        rtbs_lastSelectedStartIndex = rtb.SelectionStart;
                        rtbs_lastSelectionLength = rtb.SelectionLength;
                        //
                        rtb.SelectionBackColor = Color.LightGreen;
                        flag=  true;
                    }
                    else
                    { // didn't find a mach for the keyword, reset the index, so that it will start searching from the begenning next time.
                        lastkeyword = "";
                        rtbs_lastSelectedStartIndex = -1;
                        rtbs_lastSelectionLength = 1;
                        flag = false;
                    }
                    // scroll to selection
                    rtb.ScrollToCaret();
                }
            }
            catch 
            {
                flag = false;
            }
            return flag;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// clear the highlight from a text in rich text box.
        /// </summary>
        public void resetBgColorForSelections()
        {
            // for rich text box
            if (rtbs_Last_rtb != null && rtbs_lastSelectedStartIndex != -1)
            {
                rtbs_Last_rtb.Select(rtbs_lastSelectedStartIndex, rtbs_lastSelectionLength);
                rtbs_Last_rtb.SelectionBackColor = rtbs_lastSelectionOriginalBgColor;
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// tabs_SelectedIndexChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            /// clear the last highlight
            resetBgColorForSelections();
            try
            {
                /// add bg color for the ports
                // ib table
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(ibPortsTab.Text))
                {
                    if (loadingCompleted && !IbLeafsPortPainted)
                    {
                        /// do it in a new thread
                        (new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_IB_Ports))).Start(ibPortsDataGridView);
                        IbLeafsPortPainted = true;
                    }
                }
                // eth table
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(ethPortsTab.Text))
                {
                    if (loadingCompleted && !EthLeafsPortPainted)
                    {
                        /// do it in a new thread
                        (new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_ETH_Ports))).Start(ethPortsDataGridView);
                        EthLeafsPortPainted = true;
                    }
                }
                // spines table
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(portInfoTab.Text) && portInfoMainTab.SelectedTab.Text.Equals(portsInfoSpinesTab.Text))
                {
                    if (loadingCompleted && !spinesPortPainted)
                    {
                        /// do it in a new thread
                        (new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_IB_Ports))).Start(spinesPortInfoDataGridView);
                        spinesPortPainted = true;
                    }
                }

                // markers - run once
                if (mainPanelInnerTabs.SelectedTab.Text.Equals(messagesTab.Text) && markersRunOnce)
                {
                	(new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
                	markersRunOnce = false;
                }
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// searches for the given keyword in a DataGridView
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="keyword">keyword</param>
        /// <returns>retruns true if it finds a match for the keyword </returns>
        private bool searchInDataGridView(DataGridView dgv, string keyword)
        {
            //// declared global variables for the search function for data grid view
            //int dgvs_lastRow = 0;
            //int dgvs_lastCol = 0;

            bool flag = false;
            // clear selection
            dgv.ClearSelection();
            // reset the indexes if it's a new keyword
            if (!keyword.Equals(lastkeyword))
            {
                dgvs_lastRow = 0;
                dgvs_lastCol = 0;
                lastkeyword = keyword;
            }
            //
            int firstColOnce = dgvs_lastCol;
            int row = 0;
            int col = 0;
            try
            {
                for (row = dgvs_lastRow; row < dgv.RowCount && !flag; row++)
                {
                    for (col = firstColOnce; col < dgv.ColumnCount && !flag; col++)
                    {
                        firstColOnce = 0;
                        if (dgv[col, row].Value.ToString().ToLower().Contains(keyword.ToLower()))
                        {
                        	// select the matching cell
                        	dgv.Rows[row].Selected = true;
                            //dgv[col, row].Selected = true;
                            //dgv.FirstDisplayedScrollingColumnIndex = col;
                            dgv.FirstDisplayedScrollingRowIndex = row;
                            flag = true;
                            if (col + 1 == dgv.ColumnCount) // is it the right most cell ?
                            {
                                dgvs_lastCol = 0; // return to the first cell
                                // should move to the next row
                                if (row + 1 == dgv.RowCount) // is the next row is the last row ?
                                {
                                    dgvs_lastRow = 0;
                                    flag = false;
                                }
                                else // move to next row
                                {
                                    dgvs_lastRow = row + 1;
                                }
                            }
                            else // stay in the same row, and move to the next cell
                            {
                                dgvs_lastRow = row;
                                dgvs_lastCol = col + 1;
                            }
                        }
                    }
                }
                // if the keyword wasn't found
                if (flag == false)
                {
                    dgvs_lastRow = 0;
                    dgvs_lastCol = 0;
                    lastkeyword = "";
                }
            }
            catch
            {
                flag = false;
            }
            return flag ;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// subnetInfoDataGridView_CellClick event handler.
        /// displays the information of the chosen link.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void subnetInfoDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                int srcPortNum1 = (int)subnetInfoDataGridView.Rows[e.RowIndex].Cells["Source  Port"].Value;
                int dstPortNum1 = (int)subnetInfoDataGridView.Rows[e.RowIndex].Cells["Destination Port"].Value;
                string srcNode = (string)subnetInfoDataGridView.Rows[e.RowIndex].Cells["Source  Node"].Value;
                string dstNode = (string)subnetInfoDataGridView.Rows[e.RowIndex].Cells["Destination Node"].Value;
                // find this set in the arraylist 
                if (subnetInfoList != null)
                {
                    for (int i = 0; i < subnetInfoList.Count; i++)
                    {
                        OpensmSubnetFeilds link = (OpensmSubnetFeilds)subnetInfoList[i];
                        if (link.srcPortNum == srcPortNum1
                            && link.dstPortNum == dstPortNum1
                            && srcNode.Equals(link.srcDeviceName)
                            && dstNode.Equals(link.dstDeviceName))
                        {
                            // show the full information about those ports
                            linkInfoTextBox.Text = "Source port:\r\n\r\nDevice type: " + link.srcDeviceType + "\r\n"
                                + "Device ports number: " + link.srcDevPortsNum + "\r\n"
                                + "Device name: " + link.srcDeviceName + "\r\n"
                                + "LID: " + link.srcLid + "\r\n"
                                + "Port number: " + link.srcPortNum + "\r\n"
                                + "SystemGUID: " + link.srcSystemGUID + "\r\n"
                                + "NodeGUID: " + link.srcNodeGUID + "\r\n"
                                + "PortGUID: " + link.srcPortGUID + "\r\n"
                                + "VenID: " + link.srcVenID + "\r\n"
                                + "DevID: " + link.srcDevID + "\r\n"
                                + "Rev: " + link.srcRev + "\r\n-----------------------------\r\n\r\n";

                            linkInfoTextBox.Text += "Destination port:\r\n\r\nDevice type: " + link.dstDeviceType + "\r\n"
                                + "Device ports number: " + link.dstDevPortsNum + "\r\n"
                                + "Device name: " + link.dstDeviceName + "\r\n"
                                + "LID: " + link.dstLid + "\r\n"
                                + "Port number: " + link.dstPortNum + "\r\n"
                                + "SystemGUID: " + link.dstSystemGUID + "\r\n"
                                + "NodeGUID: " + link.dstNodeGUID + "\r\n"
                                + "PortGUID: " + link.dstPortGUID + "\r\n"
                                + "VenID: " + link.dstVenID + "\r\n"
                                + "DevID: " + link.dstDevID + "\r\n"
                                + "Rev: " + link.dstRev + "\r\n";
                            //
                            break;
                        }
                    }
                }
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// errorsRadioButton_CheckedChanged event handler
        /// toggle between full content and error only display style
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void errorsRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            setErrorTableContent();
        }
        //
        //----------------------------------------------------

        /// <summary>
        /// sets the content of error content according to the selected radio button.
        /// </summary>
        private void setErrorTableContent()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(setErrorTableContent));
            }
            else
            {
                try
                {
                    if (!isClear)
                    {
                        lock (markerLock)
                        {
                            // get the index of the currenet messages file
                            int index = errorsFromMessagesComboBox.SelectedIndex;

                            /// check if the user manually worte a value (that is not legal).
                            if (index < 0)
                            {
                                errorsFromMessagesComboBox.SelectedIndex = 0;
                                return;
                            }

                            this.SuspendLayout();
                            errorsDataGridView.SuspendLayout();

                            // reset row filter
                            DataView myDataView = ((ErrorsFields)errorsFromMessagesItems[index]).fullContent.DefaultView;
                            myDataView.RowFilter = String.Empty;
                            errorsDataGridView.DataSource = myDataView; //((ErrorsFields)errorsFromMessagesItems[index]).fullContent;

                            // show errors only 
                            if (errorsOnlyRadioButton.Checked == true)
                            {
                                //errorsDataGridView.DataSource = ((ErrorsFields)errorsFromMessagesItems[index]).errorsOnly;
                                System.Collections.Specialized.StringCollection messagesKeywords = Properties.Settings.Default.messagesKeywords;

                                // build the new filter
                                string filter = String.Empty;
                                for (int i = 0; i < messagesKeywords.Count; i++)
                                {
                                    if (i == 0)
                                    {
                                        filter = "Message LIKE '*" + Methods.EscapeLikeValue(messagesKeywords[0]) + "*'";
                                    }
                                    else
                                    {
                                        filter += " OR Message LIKE '*" + Methods.EscapeLikeValue(messagesKeywords[i]) + "*'";
                                    }
                                }
                                // if there are no configured keywords, then hide all lines..
                                if (filter.Equals(String.Empty))
                                {
                                    filter = "Message LIKE 'hide_all*'";
                                }
                                // apply the filter
                                myDataView.RowFilter = filter;

                                // put message if there were no matches
                                if (errorsDataGridView.Rows.Count == 0)
                                {
                                    DataTable tmp = new DataTable();
                                    // add columns
                                    tmp.Columns.Add("Time", typeof(DateTime));
                                    tmp.Columns.Add("Message", typeof(string));
                                    tmp.Rows.Add(DateTime.Now, "******  No matches for the defined keywords in this file.  ******");
                                    errorsDataGridView.DataSource = tmp;
                                }
                            }
                            //else // show the full content
                            //{
                            //    errorsDataGridView.DataSource = ((ErrorsFields)errorsFromMessagesItems[index]).fullContent;
                            //}
                        }// end lock
                    }
                }
                catch { }
                finally
                {
                    if (!isClear)
                    {
                        errorsDataGridView.ResumeLayout();
                        this.ResumeLayout();
                        // add markers
                        (new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
                        errorsDataGridView.Refresh();
                    }
                }
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// errorsDataGridView_CellDoubleClick event handler
        /// switch to full content view, and search for the selected message.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void errorsDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (errorsOnlyRadioButton.Checked == true)
                {
                    // get the content of the 'message' cell
                    string msg = (string)errorsDataGridView.Rows[e.RowIndex].Cells["Message"].Value;
                    // switch to full content view
                    fullRadioButton.Checked = true;
                    // search for the relevant row and select it
                    searchInDataGridView(errorsDataGridView, msg);
                }
            }
            catch { }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// refres all elements
        /// </summary>
        public void refresh()
        {
            setFontForAll();
            // update markers
            lock (markerLock)
            {
                isMarkersEnabled = true;
            }
            //(new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
            // update table based on the keyword lists
            setErrorTableContent(); // it will add markers also 
            setErrorsFromDmesgContent();

            
        }
        //
        //----------------------------------------------------

        /// <summary>
        /// change the font of all elements
        /// </summary>
        public void setFontForAll()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(setFontForAll));
            }
            else
            {
                try
                {
                    /// get the saved font
                    Font newFont = Properties.Settings.Default.myFont;
                    /// set the font for all elements
                    // chassisInfoTab
                    chassisInfoRichTextBox.Font = newFont;
                    ledIndicationsDataGridView.Font = newFont;
                    // 
                    interfaceMgmtRichTextBox.Font = newFont;
                    //knowledgeBaseTab
                    summaryTextBox.Font = newFont;
                    //systemInformationTab
                    systemInformationTextBox.Font = newFont;
                    syslogDataGridView.Font = newFont;
                    // messagesMainTab
                    errorsDataGridView.Font = newFont;
                    errorsFromDmesgTextBox.Font = newFont;
                    printGapsDataGridView.Font = newFont;
                    //configDBMain
                    runningConfigTextBox.Font = newFont;
                    configDBTextBox.Font = newFont;
                    switchConfigurationsDataGridView.Font = newFont;
                    // ibInfoTab
                    mcGroupParamTextBox.Font = newFont;
                    mcGroupDataGridView.Font = newFont;
                    subnetInfoDataGridView.Font = newFont;
                    // ethInfoMainTab
                    ethinfoTextBox.Font = newFont;
                    // ethInfoMainTab -> ISS dump
                    lagCacheTextBox.Font = newFont;
                    issdETSTextBox.Font = newFont;
                    issPortDBDataGridView.Font = newFont;
                    port_indexes_htDataGridView.Font = newFont;
                    interfaces_htDataGridView.Font = newFont;
                    issdPFCDataGridView.Font = newFont;
                    vlanMembersDataGridView.Font = newFont;
                    // processesAndMemoryTab
                    memoryUsageTextBox.Font = newFont;
                    processesDataGridView.Font = newFont;
                    // lspciTab
                    lspciTextBox.Font = newFont;
                    // asicFintLogTab
                    asicFlintLogTextBox.Font = newFont;
                    // ufmaDataTab
                    ufmaDataTextBox.Font = newFont;
                    // portInfoTab
                    ibPortsDataGridView.Font = newFont;
                    ethPortsDataGridView.Font = newFont;
                    spinesPortInfoDataGridView.Font = newFont;

                    // commandsHistoryTab
                    root_cli_historyDataGridView.Font = newFont;
                    monitor_cli_historyDataGridView.Font = newFont;
                    //filesListTab 
                    filesListDataGridView.Font = newFont;
                    // daemons tab
                    daemonsDataGridView.Font = newFont;
                    daemonsSummaryRichTextBox.Font = newFont;

                    //mstdumpOnlyTextBox
                    mstdumpOnlyTextBox.Font = newFont;
                }
                catch { }
            }
        }
        //
        //----------------------------------------------------
        
        
        /// <summary>
        ///  if we reorderd the table then we need to set the bg colors again.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spinesPortInfoDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            (new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_IB_Ports))).Start(spinesPortInfoDataGridView);
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        ///  Form1_FormClosed event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            GC.Collect();
            //GC.WaitForFullGCComplete();
            //GC.GetTotalMemory(true);
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// imageHistoryImagesOnlyRadioButton_CheckedChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imageHistoryImagesOnlyRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            /// toggle between full content and images only
            if (imageHistoryImagesOnlyRadioButton.Checked == true)
            {
                /// image only
                syslogDataGridView.DataSource = systemLogDataTables[0];
            }
            else
            {
                /// full content
                syslogDataGridView.DataSource = systemLogDataTables[1];
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// dmsegErrorOnlyRadioButton_CheckedChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dmsegErrorOnlyRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            setErrorsFromDmesgContent();
        }
        //
        //----------------------------------------------------

        private void setErrorsFromDmesgContent()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(setErrorsFromDmesgContent));
            }
            else
            {
                try
                {
                    /// toggle between full content and errors only
                    if (!isClear)
                    {
                        errorsFromDmesgTextBox.Text = "";
                        if (dmsegErrorOnlyRadioButton.Checked == true)
                        {
                            /// errors only
                            //errorsFromDmesgTextBox.Text = errorsFromDmesg[0];
                            System.Collections.Specialized.StringCollection dmesgKeywords = Properties.Settings.Default.dmesgKeywords;
                            string[] lines = Regex.Split(errorsFromDmesg, "\n");
                            if (lines != null)
                            {
                                for (int lineN = 0; lineN < lines.Length; lineN++)
                                {
                                    for (int key = 0; key < dmesgKeywords.Count; key++)
                                    {
                                        if (lines[lineN].Contains(dmesgKeywords[key]))
                                        {
                                            errorsFromDmesgTextBox.Text += lines[lineN] + "\n";
                                            break;
                                        }
                                    }
                                }
                            }
                            //
                            if (errorsFromDmesgTextBox.Text.Equals(""))
                            {
                                errorsFromDmesgTextBox.Text = "******  No matches for the defined keywords in this file.  ******";
                            }
                        }
                        else
                        {
                            /// full content
                            errorsFromDmesgTextBox.Text = errorsFromDmesg;
                        }
                    }
                }
                catch { }
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// dockButton_Click event handler.
        /// dock the tab in the main window (after it was undocked earlier).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dockButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.AllowDrop = false;
            }
            catch
            { }
            mdiParentPtr.addExistingChildForm(this);
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// undock the tab from the main window
        /// </summary>
        public void unDockTab()
        {
            try
            {
                if (isClear)
                {
                    this.AllowDrop = true;
                }
            }
            catch
            { }
            /// display the search and dock panel
            toolStrip1.Visible = true;
            /// undock it
            this.MdiParent = null;   
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// hides the search and dock panel
        /// </summary>
        public void hideDockPanel()
        {
            toolStrip1.Visible = false;
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// searchToolStripButton_Click event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchToolStripButton_Click(object sender, EventArgs e)
        {
            /// search for the keyword
            if (this.searchInCurrentTab(keywordToolStripTextBox.Text) == false)
            {
                /// indicate that the keyword wasn't found
                searchNoteToolStripLabel.Text = "Can't find this keyword!";
            }
            else
            {
                /// if the keyword was found
                searchNoteToolStripLabel.Text = "";
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// clearToolStripButton1_Click event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearToolStripButton1_Click(object sender, EventArgs e)
        {
            this.resetBgColorForSelections();
            keywordToolStripTextBox.Text = "type here to search";
            searchNoteToolStripLabel.Text = "";
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// keywordToolStripTextBox_KeyPress event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void keywordToolStripTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            /// if it was the 'Enter' button, then start the search
            if (e.KeyChar == (char)Keys.Enter)
            {
                searchToolStripButton_Click(null, null);
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// keywordToolStripTextBox_Leave event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void keywordToolStripTextBox_Leave(object sender, EventArgs e)
        {
            searchNoteToolStripLabel.Text = "";
            if (keywordToolStripTextBox.Text.Equals(""))
            {
                keywordToolStripTextBox.Text = "type here to search";
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// keywordToolStripTextBox_Click event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void keywordToolStripTextBox_Click(object sender, EventArgs e)
        {
            searchNoteToolStripLabel.Text = "";
            if (keywordToolStripTextBox.Text.Equals("type here to search"))
            {
                keywordToolStripTextBox.Text = "";
            }
        }
        //
        //----------------------------------------------------
        
        /// <summary>
        /// printGapsDataGridView_CellDoubleClick event handler
        /// find and select the messages in the full content view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printGapsDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // get the messages
                string msg1 = (string)printGapsDataGridView.Rows[e.RowIndex].Cells["Message 1"].Value;
                DateTime time1 = (DateTime)printGapsDataGridView.Rows[e.RowIndex].Cells["Time 1"].Value;
                string msg2 = (string)printGapsDataGridView.Rows[e.RowIndex].Cells["Message 2"].Value;
                DateTime time2 = (DateTime)printGapsDataGridView.Rows[e.RowIndex].Cells["Time 2"].Value;

                // switch to errors from messages tab
                errorsMainTab.SelectedTab = this.errorsInMessagesTab;

                // choose the relevant messages file from the comboBox
                string fileName = (string)printGapsDataGridView.Rows[e.RowIndex].Cells["File name"].Value;
                for (int i = 0; i < errorsFromMessagesComboBox.Items.Count; i++)
                {
                    if (errorsFromMessagesComboBox.Items[i].Equals(fileName))
                    {
                        errorsFromMessagesComboBox.SelectedIndex = i;
                        break;
                    }
                }

                // switch to full content view
                fullRadioButton.Checked = true;
                // sort
                errorsDataGridView.Sort(errorsDataGridView.Columns["Time"], ListSortDirection.Ascending);
                // search for the relevant rows and select them
                for (int row = 1; row < errorsDataGridView.Rows.Count - 1; row++)
                {
                    if (errorsDataGridView[1, row].Value.Equals(msg1)
                        && errorsDataGridView[1, row + 1].Value.Equals(msg2)
                        && errorsDataGridView[0, row].Value.Equals(time1)
                        && errorsDataGridView[0, row + 1].Value.Equals(time2))
                    {
                        errorsDataGridView.Rows[row].Selected = true;
                        errorsDataGridView.Rows[row + 1].Selected = true;
                        errorsDataGridView.FirstDisplayedScrollingRowIndex = row;
                        break;
                    }
                }
            }
            catch { }
        }
        //
        //----------------------------------------------------


        object markerLock = new object();
        /// <summary>
        /// add background color for the cells in the Messages table
        /// </summary>
        /// <param name="param">DataGridView</param>
        private void addBgColorForMessagesTable()
        {
            lock (markerLock)
            {
                if (isMarkersEnabled)
                {
                    isMarkersEnabled = false;
                    // get markers IEnumerator
                    MarkerListSett markerSettings = new MarkerListSett();
                    markerSettings.Reload();
                    IEnumerator ienum = markerSettings.Marker_List.MarkersEnumerator;

                    // mark rows
                    for (int row = 0; row < errorsDataGridView.RowCount; row++)
                    {
                        try
                        {
                            // set default bg color
                            errorsDataGridView.Rows[row].DefaultCellStyle.BackColor = Color.White;

                            ienum.Reset();
                            while (ienum.MoveNext())
                            {
                                Marker marker1 = (Marker)ienum.Current;
                                if (errorsDataGridView.Rows[row].Cells["Message"].Value != null)
                                {
                                    if (((string)errorsDataGridView.Rows[row].Cells["Message"].Value).Contains(marker1.keywork))
                                    {
                                        errorsDataGridView.Rows[row].DefaultCellStyle.BackColor = marker1.markerColor;
                                        break;
                                    }
                                }
                            }
                        }// end try
                        catch
                        { }
                    } // end for
                    isMarkersEnabled = true;
                }// end if
        	} // end lock
        }// end addBgColorForMessagesTable
        //
        //----------------------------------------------------
        
        void ErrorsDataGridViewColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        	(new Thread(new ThreadStart(addBgColorForMessagesTable))).Start();
        }
        //
        //----------------------------------------------------
        
        void EthPortsDataGridViewColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        	(new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_ETH_Ports))).Start(ethPortsDataGridView);
        }
        
        void IbPortsDataGridViewColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        	(new Thread(new ParameterizedThreadStart(addBgColorForErrorsIn_IB_Ports))).Start(ibPortsDataGridView);
        }
    } // end class
} // end namespace
